package com.pengcheng.taskapplication.net;

import android.content.Context;
import android.content.Intent;
import android.util.Log;

import com.google.gson.Gson;
import com.pengcheng.taskapplication.TaskApplication;
import com.pengcheng.taskapplication.mvp.view.activity.LoginActivity;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.lang.reflect.Type;

import okhttp3.ResponseBody;
import retrofit2.Converter;

public class MyGsonConverter<T> implements Converter<ResponseBody, T> {

    private final Gson mGson;
    private final Type mType;

    private static final String TAG = MyGsonConverter.class.getSimpleName();

    MyGsonConverter(Gson gson, Type type) {
        this.mGson = gson;
        this.mType = type;
    }

    @Override
    public T convert(ResponseBody value) throws IOException {
        String response = value.string();
        Log.d(TAG, response);
        try {
            JSONObject json = new JSONObject(response);
           if (json.optInt("code") == 500) {
                // TODO 跳转到登录界面
         //       Log.e(TAG, "接收到code返回值为：100，跳转到登录界面");
                Context context= TaskApplication.getInstance().getApplicationContext();
                Intent intent = new Intent(context, LoginActivity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                context.startActivity(intent);
            }
            Log.e("msg",response);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return new Gson().fromJson(response, mType);
    }
}
